#!/bin/bash

set -e

case "$1" in
    configure)
        RAVEN_GID=$(getent group ravendb | cut -d ':' -f 3)
        if [[ -z "$RAVEN_GID" ]]; then

            [[ -n "$RAVEN_GROUP_ID" ]] && GID_ARG="--gid $RAVEN_GROUP_ID"

            groupadd $GID_ARG ravendb
            RAVEN_GID=$(getent group ravendb | cut -d ':' -f 3)
        fi

        [[ -n "$RAVEN_USER_ID" ]] && UID_ARG="--uid $RAVEN_USER_ID"

        getent passwd ravendb || adduser --disabled-login --disabled-password --system --home /var/lib/ravendb --no-create-home --quiet $UID_ARG --gid "$RAVEN_GID" ravendb
        
        ldconfig
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

RVN_RUNTIME_DIRS=(
    /etc/ravendb
    /etc/ravendb/security
    /var/lib/ravendb
    /var/lib/ravendb/data
    /var/lib/ravendb/packages/nuget/{indexing,logging}
    /var/log/ravendb/{logs,audit}
)

for runtimeDir in "${RVN_RUNTIME_DIRS[@]}"
do

mkdir -p $runtimeDir
chown root:ravendb $runtimeDir
chmod 770 $runtimeDir 

done

chown root:ravendb /usr/lib/ravendb/server/{Raven.Server,rvn}

CREATEDUMP_PATH="/usr/lib/ravendb/server/createdump"
RAVEN_DEBUG_PATH="/usr/lib/ravendb/server/Raven.Debug"
debugBinList=("$CREATEDUMP_PATH" "$RAVEN_DEBUG_PATH")
for binFilePath in "${debugBinList[@]}"
do
    binFilename="$(basename $binFilePath)"

    echo "Adjust $binFilename binary permissions..."
    if [[ ! -f "$binFilePath" ]]; then
        echo "$binFilename binary not found in under $binFilePath. Exiting..."
        exit 2
    fi

    if command -v setcap &> /dev/null; then
        setcap cap_sys_ptrace=eip "$binFilePath"
    fi

    chown root:ravendb "$binFilePath"
    chmod +s "$binFilePath"
done

if [ ! -f /etc/ravendb/settings.json ]; then
    cp /usr/lib/ravendb/server/settings.default.json /etc/ravendb/settings.json
fi

if [ ! -f /etc/ravendb/security/master.key ]; then
    touch /etc/ravendb/security/master.key
fi

chmod 660 /etc/ravendb/security/master.key /etc/ravendb/settings.json
chown -R root:ravendb /etc/ravendb

#DEBHELPER#

if grep -e '"Setup.Mode": "Initial"' /etc/ravendb/settings.json >&/dev/null; then
    rvnPort="53700"
    fwdPort="8080"
    sshTunnelLine="ssh -N -L localhost:${fwdPort}:localhost:${rvnPort}"
    rvnServerAddr=$(egrep -e '"ServerUrl"' /etc/ravendb/settings.json | egrep -o -e 'http:[^"]+')
    user="${SUDO_USER:-username}"
    publicAddr="target-machine.com"
    if command -v dig >&/dev/null; then
        foundPublicAddr=$(dig +short myip.opendns.com @resolver1.opendns.com)
    elif command -v curl >&/dev/null; then
        foundPublicAddr=$(curl -s https://api.ipify.org)
    fi

    if [ $? -eq 0 ] && [ ! -z "$foundPublicAddr" ]; then
        publicAddr="$foundPublicAddr"
    fi

    echo "### RavenDB Setup ###"
    echo "#"
    echo "#  Please navigate to $rvnServerAddr in your web browser to complete setting up RavenDB."
    echo "#  If you set up the server through SSH, you can tunnel RavenDB setup port and proceed with the setup on your local."
    echo "#"
    echo "#  For public address:    $sshTunnelLine ${user}@${publicAddr}"
    echo "#"
    echo "#  For internal address:  $sshTunnelLine ${user}@$(hostname)"
    echo "#"
    echo "###"
fi

exit 0
